﻿package com.oet.web.freemarker;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class ReadFreemaker {
	public Configuration freemarker_cfg = null;

	public Configuration getFreeMarkerCFG(String templateUrl)
			throws IOException {
		if (this.freemarker_cfg == null) {
			this.freemarker_cfg = new freemarker.template.Configuration();
			this.freemarker_cfg.setDefaultEncoding("utf-8");
			this.freemarker_cfg.setDirectoryForTemplateLoading(new File(
					templateUrl.substring(0, templateUrl.lastIndexOf("/"))));
		}
		return this.freemarker_cfg;
	}

	public static void geneHtmlFile(String templateFilePath,
			String htmlFilePath, Map propMap) throws IOException,
			TemplateException {
		String url = templateFilePath.substring(templateFilePath
				.lastIndexOf("/") + 1, templateFilePath.length());
		File myFilePath = new File(htmlFilePath.substring(0, htmlFilePath
				.lastIndexOf("/")));
		if (!(myFilePath.exists())) {
			myFilePath.mkdirs();
		}
		ReadFreemaker sp = new ReadFreemaker();
		try {
			Template t = sp.getFreeMarkerCFG(templateFilePath).getTemplate(url);
			File afile = new File(htmlFilePath);
			Writer out = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(afile), "utf-8"));
			t.process(propMap, out);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		String templateFilePath="D://workspace/ydk//WebRoot//freemarker//a.ftl";
		String htmlFilePath="D://workspace/ydk//WebRoot//freemarker//abc.jsp";
		Map map=new HashMap();
		ArrayList list =new ArrayList();
		list.add("123");
		list.add("3432");
		list.add("fad ");
		list.add("f gadf ");
		list.add("fda ");
		list.add("df hf");
		map.put("list", list);
		try {
			geneHtmlFile(templateFilePath, htmlFilePath, map);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
	}
}